package com.pan.insist.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pan.insist.constant.CommonConstant;
import com.pan.insist.dao.RoleMapper;
import com.pan.insist.model.RoleModel;
import com.pan.insist.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author kaiji
 * @since 2019-08-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleModel> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    @Transactional(readOnly = true)
    public RoleModel getExistByFilter(RoleModel roleModel) {
        if (StringUtils.isBlank(roleModel.getId())) {
            roleModel.setId(null);
        }
        return roleMapper.getExistByFilter(roleModel);
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> getUrlByRole(List<String> codeList) {
        Set<String> urlList = roleMapper.getUrlByRole(codeList);
        if (urlList == null || urlList.size() <= 0) {
            return null;
        } else {
            return new ArrayList<>(urlList);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void saveRoleAndPurview(String roleId, String purviewIds) {
        // 先删除这个角色以前的关系
        roleMapper.deleteByRoleId(roleId);
        // 保存这个角色与权限对象集合的关系
        Arrays.asList(purviewIds.split(CommonConstant.DOC_FLAG))
                .forEach(id-> roleMapper.saveRoleAndPurview(roleId, id));
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> getRoleIdsByUserId(String userId) {
        List<RoleModel> roleModelList = roleMapper.getUser(userId);
        return roleModelList.stream().map(RoleModel::getId).collect(Collectors.toList());
    }
}
